<template>
  <div class="dialog-content clearfix">
    <div class="width270 fl">
      <div class="title">{{$t('subaccount.update_wallet')}}<span class="sub" v-if="showInfo">({{$t('subaccount.create_address_info')}})</span></div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item>
          <el-input v-model="data.address" readonly></el-input>
        </el-form-item>
        <el-form-item prop="address">
          <el-input v-model="ruleForm.address" :placeholder="$t('subaccount.new_wallet_address')"></el-input>
        </el-form-item>
        <small class="info">{{$t('subaccount.wallet_info')}}</small>
        <div class="row" v-if="!isBingEmail && loginType === 'email'">
          <el-form-item prop="email">
            <el-input readonly v-model="ruleForm.email" :placeholder="$t('subaccount.no_binding_email')"></el-input>
          </el-form-item>
          <el-button class="code-btn" type="primary" size="mini" round @click="$router.push('/setup')">{{$t('subaccount.click_set')}}</el-button>
        </div>
        <div class="row" v-else>
          <el-form-item prop="code">
            <el-input v-model="ruleForm.code" :placeholder="$t('forget.email_code_info')"></el-input>
          </el-form-item>
          <el-button class="code-btn" type="primary" size="mini" round @click="getcode" :disabled="!code.v_code_btn">{{code.codeStr}}</el-button>
        </div>
        <small class="info">{{$t('subaccount.update_wallet_info')}}</small>
        <div class="dialog-footer">
          <el-button type="primary" round @click="submit">{{$t('subaccount.btn_sure')}}</el-button>
        </div>
      </el-form>
    </div>
    <div class="width270 fr">
      <div class="title">{{$t('subaccount.update_history')}}</div>
      <div v-loading="getLoading">
        <div v-if="!address_log.length">{{$t('subaccount.no_history')}}</div>
        <ul class="list">
          <li v-for="(item,index) in address_log" :key="index">
            <div class="item"><span class="name">{{$t('subaccount.update_time')}}：</span><input class="value" :value="item.updated_at" readonly/></div>
            <div class="item"><span class="name">{{$t('subaccount.update_ip')}}：</span><input class="value" :value="item.ip" readonly/></div>
            <div class="item"><span class="name">{{$t('subaccount.address')}}：</span><input class="value" :value="item.oldaddress" readonly/></div>
            <div class="item"><span class="name">{{$t('subaccount.new_address')}}：</span><input class="value" :value="item.newaddress" readonly/></div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { updateSubaccountAddress, updateAddressLog, getcode, sendTelCode } from '@/api';
import { mapGetters, mapMutations } from 'vuex';

export default {
  props: {
    data: {
      type: Object,
    },
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!this.isBingEmail) {
        callback(new Error(this.$t('subaccount.bind_email')));
      } else {
        callback();
      }
    };
    return {
      getLoading: true,
      address_log: [],
      ruleForm: {
        address: '',
        code: '',
        email: '',
      },
      rules: {
        address: [
          {
            required: true,
            message: this.$t('subaccount.input_wallet_address'),
            trigger: 'change',
          },
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' },
        ],
        code: [
          {
            required: true,
            message: this.$t('forget.email_code_info'),
            trigger: 'change',
          },
        ],
      },
      code: {
        v_code_btn: true,
        codeStr: this.$t('btn.sendcode.getcode'),
        time: 60,
        timer: null,
      },
    };
  },
  computed: {
    ...mapGetters(['isBingEmail', 'email', 'subId', 'loginType', 'tel']),
    showInfo() {
      return ['btc', 'bch', 'bsv'].indexOf(this.data.coin_type) === -1;
    },
  },
  created() {
    this.getUpdateAddressLog();
  },
  beforeDestroy() {
    window.clearInterval(this.code.timer);
  },
  methods: {
    ...mapMutations(['SET_SUB_ADDRESS']),
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          updateSubaccountAddress({
            cuid: this.data.puid,
            coin_type: this.data.coin_type,
            config_id: this.data.config_id,
            address: this.ruleForm.address.trim(),
            code: this.ruleForm.code,
          }).then((res) => {
            if (res.data.status === 1) {
              this.$emit('toggleDialog', { showDialog: false, refresh: true });
              if (this.data.config_id === this.subId) {
                this.SET_SUB_ADDRESS(this.ruleForm.address.trim());
              }
              this.$notify({
                message: this.$t('api.6086'),
                type: 'success',
                duration: 2000,
                showClose: false,
              });
            } else {
              this.$message.error(this.$t(`api.${res.data.errcode}`));
            }
          }).catch(() => {
            this.$message.error(this.$t('error.catchError'));
          });
        }
      });
    },
    getcode() {
      this.code.v_code_btn = false;
      this.code.codeStr = `${this.$t('btn.sendcode.resend')}(60s)`;
      clearInterval(this.code.timer);
      this.code.timer = setInterval(() => {
        if (this.code.time > 0) {
          this.code.time -= 1;
          this.code.codeStr = `${this.$t('btn.sendcode.resend')}(${this.code.time}s)`;
        } else {
          clearInterval(this.code.timer);
          this.code.time = 60;
          this.code.codeStr = this.$t('btn.sendcode.sendcode');
          this.code.v_code_btn = true;
        }
      }, 1000);
      if (this.loginType === 'email') {
        getcode({
          email: this.email,
          type: 'set_wallet',
        }).then((res) => {
          if (res.data.status === 1) {
            this.$notify({
              message: this.$t('set.send_email_code'),
              type: 'success',
              duration: 2000,
              showClose: false,
            });
          } else {
            this.$message({
              message: this.$t(`api.${res.data.errcode}`),
              type: 'warning',
            });
          }
        }).catch(() => {
          this.$message.error(this.$t('error.catchError'));
        });
      } else {
        sendTelCode({
          tel: this.tel,
          type: 'set_wallet',
        }).then((res) => {
          if (res.data.status === '1') {
            this.$notify({
              message: this.$t('set.send_phone_code'),
              type: 'success',
              duration: 2000,
              showClose: false,
            });
          } else {
            this.$message({
              message: this.$t(`api.${res.data.errcode}`),
              type: 'warning',
            });
          }
        }).catch(() => {
          this.$message.error(this.$t('error.catchError'));
        });
      }
    },
    getUpdateAddressLog() {
      this.getLoading = true;
      updateAddressLog({
        cuid: this.data.puid,
        coin_type: this.data.coin_type,
        config_id: this.data.config_id,
      }).then((res) => {
        if (res.data.status === 1) {
          this.address_log = res.data.data;
        }
        this.getLoading = false;
      }).catch(() => {
        this.getLoading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-content {
  width: 740px;
  padding: 0 50px;
  .title {
    padding: 42px 0 22px;
    .sub{
      font-size: 14px;
      color: red;
      margin-left: 5px;
    }
  }
  .row{
    position: relative;
    .code-btn{
      padding: 0 7px;
      position: absolute;
      right: 5px;
      bottom: 20px;
      /deep/ span {
        line-height: 18px;
      }
    }
  }
  .list{
    height: 412px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      width: 2px;
      height: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #ddd;
      border: thin solid lightgray;
      box-shadow: 0px 0px 2px #f6f6f6 inset;
      -moz-box-shadow: 0px 0px 2px #f6f6f6 inset;
      -webkit-box-shadow: 0px 0px 2px #f6f6f6 inset;
      -o-box-shadow: 0px 0px 2px #f6f6f6 inset;
    }
    &::-webkit-scrollbar-thumb {
      background: #373737;
      border: thin solid #000;
    }
    li{
      border-bottom: 2px solid #ccc;
      .item{
        display: flex;
        border-bottom: 1px solid #e4e4e4;
        &:last-of-type{
          border-bottom: none;
        }
        padding: 10px 5px;
        .name{
          color: #ccc;
        }
        .value{
          color: #ccc;
          width: auto;
          flex: 1;
          border-bottom: none;
          padding: 0;
          margin-bottom: 0;
        }
      }
    }

  }
  .dialog-footer{
    padding-top: 30px;
  }
}
</style>
